package me.zhengjie.modules.system.rest;

import lombok.SneakyThrows;
import me.zhengjie.modules.system.domain.Courseresourcesmsg;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.CourseresourcesmsgService;
import me.zhengjie.modules.system.service.ResourceService;
import org.springframework.core.io.*;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
//import me.zhengjie.modules.system.domain.Resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {
    public Path currentWorkingDirectory = Paths.get("");
    public String projectPath = currentWorkingDirectory.toAbsolutePath().getParent().toString()+"/upload/";

    private final ResourceService resourceService;

    private final CourseresourcesmsgService courseresourcesmsgService;

    public FileUploadController(ResourceService resourceService, CourseresourcesmsgService courseresourcesmsgService) {
        this.resourceService = resourceService;
        this.courseresourcesmsgService = courseresourcesmsgService;
    }

    //    private static final String UPLOADED_FOLDER = "D:/upload/";
    public static String generateTimestampFileName(String originalFileName) {
        // 使用 SimpleDateFormat 创建时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        // 生成时间戳
        String timestamp = sdf.format(new Date());
        // 获取原始文件的扩展名
        String fileExtension = getFileExtension(originalFileName);
        String fileName = originalFileName.substring(originalFileName.lastIndexOf("/")+1, originalFileName.lastIndexOf("."));
        // 返回带有时间戳的新文件名
        return fileName+timestamp + "." + fileExtension;
    }

    public static String getFileExtension(String fileName) {
        // 获取文件的扩展名
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
    @PostMapping("/upload")
    public ResponseEntity<Object> handleFileUpload(@RequestParam("file") MultipartFile file) {

        me.zhengjie.modules.system.domain.Resource rescourseInit = new me.zhengjie.modules.system.domain.Resource();
        rescourseInit.setName(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
        rescourseInit.setFileNmae(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        switch (fileType) {
            case "png":
            case "jpg":
            case "jpeg":
            case "bmp":
            case "gif":
                rescourseInit.setType(0);
                break;
            case "mp3":
            case "wav":
                rescourseInit.setType(1);
                break;
            case "mp4":
            case "avi":
            case "mov":
                rescourseInit.setType(2);
                break;
            case "doc":
            case "xls":
            case "ppt":
            case "pdf":
            case "txt":
            case "docx":
            case "xlsx":
            case "pptx":
                rescourseInit.setType(6);
                break;
        }
        rescourseInit.setState(0);
        rescourseInit.setIsOpen(0);

        if (file.isEmpty()) {
            return new ResponseEntity<>("文件为空，请选择有效文件上传。",HttpStatus.OK);
        }
        try {
            // 允许的文件扩展名
//            List<String> allowedExtensions = Arrays.asList("png", "jpg", "jpeg", "mp4","pdf");
            List<String> allowedExtensions = Arrays.asList("png", "jpg", "jpeg","bmp","gif",
                    "mp3","wav",
                    "mp4","avi","mov",
                    "doc","xls","ppt","pdf","txt","docx","xlsx","pptx");

            String fileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if (!allowedExtensions.contains(fileExtension)) {

                return new ResponseEntity<>("上传失败，只允许PNG、JPG、JPEG、PDF和MP4格式的文件",HttpStatus.OK);
            }
            if (rescourseInit.getType() == 0 && file.getSize() > 1024*1024*50) { // 检查文件大小

                return new ResponseEntity<>("图片文件大小超出限制",HttpStatus.OK);
            } else if(file.getSize() > 1024*1024*1024){
                return new ResponseEntity<>("文件大小超出限制",HttpStatus.OK);

            }


            // 获取文件存储路径，这里假设是在项目根目录下的uploads文件夹

            String fileName = generateTimestampFileName(file.getOriginalFilename());
            String directoryPath = Paths.get(projectPath,fileName).toString();
            File directory = new File(projectPath);
            String filePath = directoryPath;
            if (!directory.exists()) {
                // 创建目录
                boolean result = directory.mkdir();
                if (result) {
                    System.out.println("目录创建成功：" + directoryPath);
                    filePath = Paths.get(directoryPath, file.getOriginalFilename()).toString();


                } else {
                    System.out.println("目录创建失败：" + directoryPath);
                }
            } else {
                System.out.println("目录已存在：" + directoryPath);
            }
            // 保存文件
            file.transferTo(new File(filePath));
            rescourseInit.setUrl("/upload/"+fileName);
            resourceService.create(rescourseInit);
//            return filePath;
            return new ResponseEntity<>("/upload/"+fileName,HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
//            return "文件上传失败：" + e.getMessage();
            return new ResponseEntity<>("文件上传失败：" + e.getMessage(),HttpStatus.OK);
        }


    }

    @PostMapping("/uploadCourseResource")
    public ResponseEntity<Object> uploadCourseResource(@RequestParam("file") MultipartFile file,@RequestParam("courseResourcesCatalogId") Integer courseResourcesCatalogId,@RequestParam("courseResourcesId") Integer courseResourcesId) {


        me.zhengjie.modules.system.domain.Courseresourcesmsg rescourseInit = new me.zhengjie.modules.system.domain.Courseresourcesmsg();
        rescourseInit.setName(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
        rescourseInit.setFilenmae(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        switch (fileType) {
            case "png":
            case "jpg":
            case "jpeg":
            case "bmp":
            case "gif":
                rescourseInit.setType(0);
                break;
            case "mp3":
            case "wav":
                rescourseInit.setType(1);
                break;
            case "mp4":
            case "avi":
            case "mov":
                rescourseInit.setType(2);
                break;
            case "doc":
            case "xls":
            case "ppt":
            case "pdf":
            case "txt":
            case "docx":
            case "xlsx":
            case "pptx":
                rescourseInit.setType(6);
                break;
        }
        rescourseInit.setState(0);
        rescourseInit.setIsopen(0);

        if (file.isEmpty()) {
            return new ResponseEntity<>("文件为空，请选择有效文件上传。",HttpStatus.OK);
        }
        try {
            // 允许的文件扩展名
//            List<String> allowedExtensions = Arrays.asList("png", "jpg", "jpeg", "mp4","pdf");
            List<String> allowedExtensions = Arrays.asList("png", "jpg", "jpeg","bmp","gif",
                    "mp3","wav",
                    "mp4","avi","mov",
                    "doc","xls","ppt","pdf","txt","docx","xlsx","pptx");

            String fileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if (!allowedExtensions.contains(fileExtension)) {

                return new ResponseEntity<>("上传失败，只允许PNG、JPG、JPEG、PDF和MP4格式的文件",HttpStatus.OK);
            }
            if (rescourseInit.getType() == 0 && file.getSize() > 1024*1024*50) { // 检查文件大小

                return new ResponseEntity<>("图片文件大小超出限制",HttpStatus.OK);
            } else if(file.getSize() > 1024*1024*1024){
                return new ResponseEntity<>("文件大小超出限制",HttpStatus.OK);

            }


            // 获取文件存储路径，这里假设是在项目根目录下的uploads文件夹
            String fileName = generateTimestampFileName(file.getOriginalFilename());
            String directoryPath = Paths.get(projectPath,fileName).toString();
            File directory = new File(projectPath);
            String filePath = directoryPath;
            if (!directory.exists()) {
                // 创建目录
                boolean result = directory.mkdir();
                if (result) {
                    System.out.println("目录创建成功：" + directoryPath);
                    filePath = Paths.get(directoryPath, file.getOriginalFilename()).toString();


                } else {
                    System.out.println("目录创建失败：" + directoryPath);
                }
            } else {
                System.out.println("目录已存在：" + directoryPath);
            }
            // 保存文件
            file.transferTo(new File(filePath));
            rescourseInit.setUrl("/upload/"+fileName);

            rescourseInit.setCourseresourcescatalogId(courseResourcesCatalogId);
            rescourseInit.setCourseresourcesId((courseResourcesId));

            LocalDateTime now = LocalDateTime.now();
            // 定义日期时间格式化器，使用 yyyy-MMM-dd hh:mm:ss 格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
            // 将 LocalDateTime 按照定义的格式进行格式化
            String formattedDateTime = now.format(formatter);

            rescourseInit.setCreatetime(formattedDateTime);
            courseresourcesmsgService.create(rescourseInit);

//            return filePath;
            return new ResponseEntity<>("/upload/"+fileName,HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
//            return "文件上传失败：" + e.getMessage();
            return new ResponseEntity<>("文件上传失败：" + e.getMessage(),HttpStatus.OK);
        }


    }

    @PostMapping("/uploadIcon")
    public ResponseEntity<Object> handleFileUploadAutoSave(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return new ResponseEntity<>("文件为空，请选择有效文件上传。",HttpStatus.OK);
        }
        try {
            // 允许的文件扩展名
//            List<String> allowedExtensions = Arrays.asList("png", "jpg", "jpeg", "mp4","pdf");
            List<String> allowedExtensions = Arrays.asList("png", "jpg", "jpeg","bmp","gif","mp3","wav",
                    "mp4","avi","mov","doc","xls","ppt","pdf","txt","docx","xlsx","pptx");

            String fileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if (!allowedExtensions.contains(fileExtension)) {

                return new ResponseEntity<>("上传失败，只允许PNG、JPG、JPEG、PDF和MP4格式的文件",HttpStatus.OK);
            }
            if (file.getSize() > 100000000) { // 检查文件大小

                return new ResponseEntity<>("文件大小超出限制",HttpStatus.OK);
            }

            // 获取文件存储路径，这里假设是在项目根目录下的uploads文件夹




            System.out.println(projectPath);
            String fileName = generateTimestampFileName(file.getOriginalFilename());
            String directoryPath = Paths.get(projectPath,fileName).toString();
            File directory = new File(projectPath);
            String filePath = directoryPath;
            if (!directory.exists()) {
                // 创建目录
                boolean result = directory.mkdir();
                if (result) {
                    System.out.println("目录创建成功：" + directoryPath);
                    filePath = Paths.get(directoryPath, file.getOriginalFilename()).toString();


                } else {
                    System.out.println("目录创建失败：" + directoryPath);
                }
            } else {
                System.out.println("目录已存在：" + directoryPath);
            }
            // 保存文件
            file.transferTo(new File(filePath));

//            return filePath;
            return new ResponseEntity<>("/upload/"+fileName,HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
//            return "文件上传失败：" + e.getMessage();
            return new ResponseEntity<>("文件上传失败：" + e.getMessage(),HttpStatus.OK);
        }


    }

//    public ResponseEntity<Object> downloadFile(@PathVariable String fileId) {
//
//        // 调用服务来根据文件ID查找文件
//        File file = findFileById(fileId);
//        if (file == null) {
//            return ResponseEntity.notFound().build();
//        }
//        // 将文件作为HTTP响应返回
////        return new ResponseEntity<>(new FileSystemResource(file),HttpStatus.OK);
//        return ResponseEntity.ok()
//                .contentType(MediaType.parseMediaType("application/octet-stream"))
//                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file + "\"")
//                .body(file);
//    }
    @SneakyThrows
    @GetMapping(value="/findFile/upload/{filename:.+}")
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
////        System.out.println("==filename=="+filename);
        File file = findFileById(filename);

//        System.out.println("==file=="+file);
        if(file!=null){
            String contentType = Files.probeContentType(Paths.get(file.toURI()));
//            byte[] fileContent = new byte[(int) file.length()];
//            FileInputStream fis = new FileInputStream(file);
//            fis.read(fileContent);
//            fis.close();
//            return ResponseEntity.ok()
//                    .body(fileContent);
//            String contentType = getContentType(file);

//            Resource file2 = new FileSystemResource(file);

            FileInputStream fs = new FileInputStream(file);
//                ByteArrayOutputStream baos =new ByteArrayOutputStream();

            byte[] data2 = new byte[fs.available()];
            fs.read(data2,0,fs.available());
            System.out.println(data2.length);

            Resource resource = new ByteArrayResource(data2) {
                @Override
                public String getFilename() {
                    // 返回图片的文件名，这将帮助浏览器正确显示图片
                    return file.getName();
                }
            };
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } else {
            return new ResponseEntity<>(null,HttpStatus.OK);
        }



    }

    public File findFileById(String fileName) {
        // Find the file by ID (in this case, the file name)
        File file = new File(projectPath, fileName);
        return file.exists() ? file : null;
    }
}
